<template>
  <div id="meta-kanban-anal-manager">
    <v-header title="指标元素定义" :showDownloadBtn="false" :saveShow="false"></v-header>
    <div class="meta-kanban-anal-manager-box">
      <el-container>
      <el-header class="header-tool-bar" height="50px">
        <!--工具栏-->
        <el-row>
          <el-button type="primary" size="mini" @click="adddialogForm">增加</el-button>
          <el-button type="primary" size="mini" @click.stop="removedata">删除</el-button>
          <el-button type="primary" size="mini" @click="handleEdit">编辑</el-button>
          <el-button type="primary" size="mini" @click="refresh">刷新</el-button>
          <span class="condition-query">
              <el-input v-model="condition" size="mini" prefix-icon="el-icon-search" placeholder="请输入内容"
                        clearable></el-input>
              <el-button type="primary" size="mini" @click="queryForPage">查询</el-button>
            </span>
        </el-row>
      </el-header>
      <el-main>
        <!-- 表单 -->
        <el-table
          ref="table"
          :data="tableData"
          @selection-change="handleSelectionChange"
          @select="checkrow"
          v-model="checked"
          v-loading="tableLoading"
          tooltip-effect="dark"
          style="width: 100%">
          <el-table-column type="selection" width="auto"></el-table-column>
          <el-table-column prop="kanban_elem_name" label="看板元素名称" width="auto"></el-table-column>
          <el-table-column prop="value1" label="事件属性" width="auto"></el-table-column>
          <el-table-column prop="value2" label="业务指标" width="auto"></el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pagesize"
          layout="total, prev, pager, next"
          :total="totalCount">
        </el-pagination>
      </el-main>
    </el-container>
    </div>
    <!-- 新增/编辑-弹窗 -->
    <el-dialog :title="addRoleDialogMode === 'ADD' ? '新增数据' : '编辑数据'"
               :visible.sync="addRoleDialogVisiable"
               v-model="addRoleDialogMode"
               @close="cancel"
    >
      <el-form :model="ruleForm" :rules="rules"  ref="ruleForm" label-width="150px" class="demo-ruleForm">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="看板元素名称" prop="kanban_elem_name">
              <el-input v-model="ruleForm.kanban_elem_name" disabled class="input-size"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item prop="value1" label="事件属性">
              <el-select v-model="ruleForm.value1" placeholder="请选择" popper-class="zIndex-popper">
                <el-option
                  v-for="elmitem in elm_onelist"
                  :key="elmitem.meta_id"
                  :label="elmitem.colume_chs"
                  :value="elmitem.meta_id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="value2" label="业务指标">
              <el-select v-model="ruleForm.value2" placeholder="请选择" popper-class="zIndex-popper">
                <el-option
                  v-for="elmitem in elm_twolist"
                  :key="elmitem.meta_id"
                  :label="elmitem.tgt_name"
                  :value="elmitem.meta_id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="技术描述" prop="tech_desc">
              <el-input v-model="ruleForm.tech_desc" class="input-size"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务描述" prop="busi_desc">
              <el-input v-model="ruleForm.busi_desc" class="input-size"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item id="dialogbtn">
          <el-button @click="resetForm('ruleForm')">重置</el-button>
          <el-button @click="cancel('ruleForm')">关闭</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
  import ajax from '../../../../api/ajax/ajax'
  import { VHeader } from '../../../../components'
  import api from '../../../../api/url'
  export default {
    name: 'meta-kanban-tgt-manager',
    components: {
      VHeader
    },
    data () {
      return {
        value1: '',
        value2: '',
        elm_onelist: [],
        elm_twolist: [],
        tableLoading: true,
        condition: '', // 输入条件
        addRoleDialogVisiable: false,
        editdialogform: false,
        currentPage: 1, // 当前页码
        pagesize: 10, // 默认每页数据量
        totalCount: 0, // 默认数据总数
        checked: false,
        tableData: [],
        checkbox: [],
        addRoleDialogMode: 'ADD', // 对话框色对话框模式  ADD新增 MODIFY 修改
        list: [],
        download: false,
        save: false,
        kanban_type: 'tgt',
        searchCriteria02: 'tgt',
        ruleForm: {
          kanban_elem_name: '',
          busi_desc: '',
          tech_desc: '',
          value1: '',
          value2: ''
        },
        rules: {
          busi_desc: [
            {max: 150, message: '最多输入150个字符', trigger: 'blur'}
          ],
          tech_desc: [
            {max: 150, message: '最多输入150个字符', trigger: 'blur'}
          ],
          value1: [
            {required: true, message: '请选择', trigger: 'blur'}
          ],
          value2: [
            {required: true, message: '请选择', trigger: 'blur'}
          ]
        },
        currentItem: {},
        elm_name1: '',
        elm_name2: ''
      }
    },
    watch: {
      'ruleForm.value1' (val) {
        for (let i = 0; i < this.elm_onelist.length; i++) {
          if (val === this.elm_onelist[i].meta_id) {
            this.elm_name1 = this.elm_onelist[i].colume_chs
            break
          }
        }
        if (val && this.ruleForm.value2) {
          this.ruleForm.kanban_elem_name = `${this.elm_name1}(${this.elm_name2})`
        } else if (val) {
          this.ruleForm.kanban_elem_name = this.elm_name1
        }
      },
      'ruleForm.value2' (val) {
        for (let i = 0; i < this.elm_twolist.length; i++) {
          if (val === this.elm_twolist[i].meta_id) {
            this.elm_name2 = this.elm_twolist[i].tgt_name
            break
          }
        }
        if (val && this.ruleForm.value1) {
          this.ruleForm.kanban_elem_name = `${this.elm_name1}(${this.elm_name2})`
        }
      }
    },
    created () { // 创建之前
      this.queryForPage()
      this.elm_onelist = JSON.parse(sessionStorage.getItem('commonData')).META_COLUME
      this.elm_twolist = JSON.parse(sessionStorage.getItem('commonData')).META_TGT
    },
    methods: {
      // 每页显示条目个数
      handleSizeChange (val) {
        this.pagesize = val
        this.handleCurrentChange()
      },
      queryForPage () {
        const pagelistdata = {
          keyword: this.condition,
          pageNo: this.currentPage,
          pageSize: this.pagesize,
          searchCriteria02: this.searchCriteria02
        }
        ajax.post(api.SELECT_BA_KANBAN_ELEM_DEF_LIST_FORPAGE, pagelistdata).then((res) => {
          this.tableLoading = false
          this.tableData = []
          this.tableData = res.data.list
          this.totalCount = res.data.total
          this.checked = false // 清除选中状态
          for (var i = 0; i < this.tableData.length; i++) {
             var rawdata = this.tableData[i].kanban_elem_name
             rawdata = /(.+)?(?:\(|（)(.+)(?=\)|）)/.exec(rawdata)
              var newrawdata = this.tableData[i]
              newrawdata.value1 = rawdata[1]
              newrawdata.value2 = rawdata[2]
          }
        })
      },
      // 当前页数
      handleCurrentChange (val) {
        this.currentPage = val
        this.queryForPage()
      },
      // 增加按钮
      adddialogForm () {
        this.ruleForm = {}
        this.currentItem = {}
        this.$refs.table.clearSelection() // 点击新增清除选中状态
        this.checked = false
        this.addRoleDialogVisiable = true
        this.addRoleDialogMode = 'ADD'
      },
      // 关闭
      cancel (formName) {
        // this.$refs.ruleForm.clearValidate()
        // this.ruleForm = {}
        this.$refs.ruleForm.resetFields() // 移除校验 重置为初始状态
        this.addRoleDialogVisiable = false
        this.editdialogform = false
        this.ruleForm = this.currentItem
        this.checked = false
        this.handleSizeChange()
      },
      // 重置
      resetForm () {
        this.ruleForm = {...this.currentItem}
        this.$refs.ruleForm.clearValidate()
      },
      // 删除数据
      removedata () {
        if (this.list.length > 0) {
          this.$confirm('是否删除该记录?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let remdata = {
              key_list: this.list
            }
            ajax.post(api.DELETE_BA_KANBAN_ELEM_DEF, remdata).then((res) => {
              this.handleSizeChange()
            })
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }).catch(() => {
          })
        } else {
          this.$message.error('请至少选择一条记录进行删除')
        }
      },
      handleSelectionChange (val) {
        // 判断是不是全选
        this.checkbox = val
        this.list = []
        for (let i = 0; i < val.length; i++) {
          let remdata = {
            kanban_elem_id: val[i].kanban_elem_id,
            created_by: val[i].created_by
          }
          this.list.push(remdata)
        }
      },
      checkrow (row) {
        if (row.length > 0) {
          let values = row[0].message_content.split('__')
          values.forEach(item => {
            if (item.indexOf('MC') !== -1) {
              this.ruleForm.value1 = item
            } else if (item.indexOf('MG') !== -1) {
              this.ruleForm.value2 = item
            }
          })
          this.ruleForm = Object.assign(this.ruleForm, row[0])
          this.checkbox = row
          this.checked = true
        } else {
          this.checked = false
        }
      },
      // 编辑
      handleEdit (row) {
        // 判断是否勾选
        if (this.checkbox.length > 0) {
          if (this.checkbox.length < 2) {
            this.addRoleDialogVisiable = true // 显示弹框
            this.addRoleDialogMode = 'MODIFY' // 新增角色对话框模式 编辑模式
            this.currentItem = JSON.parse(JSON.stringify(this.ruleForm))
            this.ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
          } else {
            this.$message.error('只能选择一条')
          }
        } else {
          this.$message.error('请至少选择一条记录进行编辑')
        }
      },
      refresh () {
        this.handleSizeChange()
      },
      // 新增/修改 元事件
      submitForm (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const insertdata = {
              kanban_elem_name: this.ruleForm.kanban_elem_name,
              busi_desc: this.ruleForm.busi_desc,
              tech_desc: this.ruleForm.tech_desc,
              created_by: this.ruleForm.created_by,
              kanban_elem_id: this.ruleForm.kanban_elem_id,
              kanban_type: this.kanban_type,
              message_content: `${this.ruleForm.value1}__${this.ruleForm.value2}`
            }
            const updatedata = {
              kanban_elem_name: this.ruleForm.kanban_elem_name,
              busi_desc: this.ruleForm.busi_desc,
              tech_desc: this.ruleForm.tech_desc,
              created_by: this.ruleForm.created_by,
              kanban_elem_id: this.ruleForm.kanban_elem_id,
              message_content: `${this.ruleForm.value1}__${this.ruleForm.value2}`
            }
            if (this.addRoleDialogMode === 'ADD') {
              // 新增接口
              ajax.post(api.INSERT_BA_KANBAN_ELEM_DEF, insertdata).then((res) => {
                this.handleSizeChange()
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                })
              })
            } else if (this.addRoleDialogMode === 'MODIFY') {
              // 修改接口
              ajax.post(api.UPDATE_BA_KANBAN_ELEM_DEF, updatedata).then((res) => {
                this.ruleForm = {}
                this.checkbox = []
                this.handleSizeChange()
                this.$message({
                  type: 'success',
                  message: '编辑成功!'
                })
              })
            }
            this.addRoleDialogVisiable = false
          } else {
            return false
          }
        })
      }
    }
  }
</script>
<style lang="stylus" rel="stylesheet/stylus">
  #meta-kanban-anal-manager
    height 100%
    overflow hidden
    .meta-kanban-anal-manager-box
      overflow auto
      height calc(100% - 66px)
      margin 10px 0 0 10px
      padding-right 10px
      .header-tool-bar
        line-height 50px
        vert-align middle
        background-color #FFFFFF
        .condition-query
          width 300px
          float right
          margin-right -10px
        .el-input--mini
          width 200px
        .el-button--danger
          background-color #016DFB
          border-color #016DFB
        .dialog-input
          width 210px
          height 30px
          border-radius 4px
          border 1px solid #D8DCE5
    .el-dialog
      width 900px
      padding-right 30px
      .el-dialog__body
        margin 0 auto
        padding 20px 20px
        .el-form
          .el-row
            .el-col-12
              .el-form-item
                .el-form-item__content
                  .el-input
                    .el-input__inner
                      height 41px
                  .el-select
                    width 100%
                    height 41px
                    margin 0
      .btn-center
        text-align center
  #dialogbtn
    margin-left 440px
  #input-size
    height 40px
</style>
